﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spinning.Spinning.Unitity;
using Microsoft.Xna.Framework;
using Microsoft.Devices.Sensors;
using System.Net;

namespace Spinning.Spinning.Entity.Scenes
{
    class HostScene : PracticeScene
    {
        Vector3 _accelReading = new Vector3();
        Vector3 _accelReadingEnemy = new Vector3();
        PracticePlayer Enemy;
        private UdpAnySourceMulticastChannel Channel { get; set; }
        TextEntity te;

        public HostScene()
            : base()
        {
            //Game1._acceleMeter.ReadingChanged += GSensorChanged;
            Game1._acceleMeter.CurrentValueChanged += GSensorChanged;
            try
            {
                Game1._acceleMeter.Start();
            }
            catch (AccelerometerFailedException e) { throw e; }
            catch (UnauthorizedAccessException e) { throw e; }
        }

        void GSensorChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        {
            _accelReading.X = (float)e.SensorReading.Acceleration.X;
            _accelReading.Y = -(float)e.SensorReading.Acceleration.Y;
            _accelReading.Z = (float)e.SensorReading.Acceleration.Z;
        }

        public override void OnLoad()
        {
            base.OnLoad();
            Enemy = new PracticePlayer();
            Enemy.textureName = "spinning";
            Enemy.OnLoad();
            Enemy.SetAnimation(Constants.playerAnimationFrame);
            Enemy.OnCreatBody(World, PhysicConnectManager);
            Enemy.BodyPosiotion = new Vector2(240, 200);
            this.Attach(Enemy);

            te = new TextEntity();
            ResourceManager.ContentRoot = "";
            te.fontString = "TestFont";
            te.OnLoad();
            te.Origin = new Vector2(0.5f);
            te.Position = new Vector2(200, 200);
            te.Color = Color.Blue;
            //te.Alpha = 0;
            te.ZIndex = Constants.debugText;
            Attach(te);


            this.Channel = new UdpAnySourceMulticastChannel(IPAddress.Parse("224.0.1.100"), 3000);
            this.Channel.AfterOpen += new EventHandler(Channel_AfterOpen);
            this.Channel.BeforeClose += new EventHandler(Channel_BeforeClose);
            this.Channel.PacketReceived += new EventHandler<UdpPacketReceivedEventArgs>(Channel_PacketReceived);

            this.Channel.Open();
        }

        void Channel_BeforeClose(object sender, EventArgs e)
        {
            this.Channel.Send("END,{0}, leaves the UDP Multicast chat,", Game1.hostId);
        }

        void Channel_AfterOpen(object sender, EventArgs e)
        {
            this.Channel.Send("BEGIN,{0}, enters the UDP Multicast chat,", Game1.hostId);
        }

        //沒用到Channel.close(); 範例也沒
        int tempCounter;

        void Channel_PacketReceived(object sender, UdpPacketReceivedEventArgs e)
        {
            //if(e.Message.Length!=0)
            //te.Value = e.Message;

            string[] temp;
            string[] temp1;

            temp = e.Message.Split(',');

            NoKeyFoundDictionary dataDictionary = new NoKeyFoundDictionary();

            bool partyFlag = false;

            for (int i = 0; i < temp.Length; i++)
            {
                temp1 = temp[i].Split(':');
                if (temp1.Length >= 2)
                    dataDictionary.Add(temp1[0], temp1[1]);
            }



            if (dataDictionary.Get("hostId") == Game1.hostId && dataDictionary.Get("clientId") == Game1.clientId && dataDictionary.Get("isHost") == "False") //client 來的封包
            {
                partyFlag = true;
            }
            else
            {
                partyFlag = false;
            }

            if (partyFlag)
            {
                _accelReadingEnemy.X = float.Parse(dataDictionary.Get("accX"));
                _accelReadingEnemy.Y = float.Parse(dataDictionary.Get("accY"));
                _accelReadingEnemy.Z = float.Parse(dataDictionary.Get("accZ"));
                Enemy.Accelerometer = _accelReadingEnemy;
                tempCounter++;
                te.Value = "Count:" + tempCounter;
                //te.Value = "X:" + _accelReadingEnemy.X + ", Y:" + _accelReadingEnemy.Y + ", Z:" + _accelReadingEnemy.X;
            }

            //if (temp.Length > 3 && temp[0] == Game1.clientId)
            //{
            //    //te.Value = "Received (X,Y,Z): (" + temp[1] + "," + temp[2] + "," + temp[3] + ")";
            //    _accelReadingEnemy.X = float.Parse(temp[1]);
            //    _accelReadingEnemy.Y = float.Parse(temp[2]);
            //    _accelReadingEnemy.Z = float.Parse(temp[3]);
            //    Enemy.Accelerometer = _accelReadingEnemy;
            //}
        }

        int tempTimer = 0;
        protected override void UpdateSelf(GameTime gameTime)
        {
            base.UpdateSelf(gameTime);
            Player.Accelerometer = _accelReading;
            int delta = gameTime.ElapsedGameTime.Milliseconds;
            tempTimer += delta;
            if (tempTimer / 50 >= 1)
            {
                tempTimer = tempTimer % 50;
                this.Channel.Send("hostId:{0},clientId:{1},playerPosX:{2},playerPosY:{3},enemyPosX:{4},enemyPosY:{5},isHost:True,", Game1.hostId, Game1.clientId, Player.Position.X, Player.Position.Y, Enemy.Position.X, Enemy.Position.Y);
                //this.Channel.Send("{0},{1},{2},{3},{4},", Game1.hostId, Player.Position.X, Player.Position.Y, Enemy.Position.X, Enemy.Position.Y);
            }
        }

        public override Scene Clone()
        {
            Scene scene = new HostScene();
            scene.Size = new Vector2(Constants.Window_Width, Constants.Window_Height);
            scene.OnLoad();
            scene.SortChildren();
            return scene;
        }
    }
}
